package main

import (
	"BiYeProServer/src/config"
	"BiYeProServer/src/model/dao"
	"BiYeProServer/src/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"github.com/robfig/cron"
	"net/http"
)

func main() {
	// 项目初始化
	initPro()
}

var db *gorm.DB
var err error

func initPro() {
	initDb()
	go initCron()
	initServer()
	defer db.Close()
}

func initCron() {
	cron2 := cron.New() //创建一个cron实例

	//执行定时任务（每5秒执行一次）
	err := cron2.AddFunc("0 */5 * * * ?", util.CronLogin)
	if err != nil {
		fmt.Println(err)
	}

	//启动/关闭
	cron2.Start()
	defer cron2.Stop()
	select {
	//查询语句，保持程序运行，在这里等同于for{}
	}
}

func initServer() {
	// Engin
	router := gin.Default()
	router.Use(Cors()) //解决跨域

	for key, value := range config.GetRouter {
		router.GET(key, value)
	}

	for key, value := range config.PostRouter {
		router.POST(key, value)
	}
	// 指定地址和端口号
	err := router.Run("localhost:8888")
	if err != nil {
		panic(err)
	}
}

func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,type,token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "true")
		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}
		context.Next()
	}
}

func initDb() {
	db, err = dao.InitDb()
}

func checkErr() {
	if err != nil {
		fmt.Println(err)
		err = nil
	}
}
